/*
 * @(#)DefaultExceptionHandler.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.exception;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.usf.core.call.Fault;
import com.nhncorp.usf.core.service.ServiceExecutionContext;
import com.nhncorp.usf.core.util.ErrorUtil;

/**
 * DefaultExceptionHandler 클래스
 * 
 * 
 * @author Web Platform Development Team
 */
public class DefaultExceptionHandler extends BaseExceptionHandler {
    Log log = LogFactory.getLog(DefaultExceptionHandler.class);

    /**
     * implement DefaultExceptionHandler
     *
     * @param fault   the fault
     * @param context the ServiceExecutionContext
     * @throws Exception the Exception
     */
    @Override
    public void handle(Fault fault, ServiceExecutionContext context) throws Exception {
        log.error(getErrorMessage(fault, context.getAction().getId(), context.getBo().getId(),
                                  context.getMethod().getName(), context.getMethodParameter()));
        handle(fault);
    }

    /**
     * Handle.
     *
     * @param fault the fault
     * @throws Exception the exception
     */
    private void handle(Fault fault) throws Exception {
        String errorCode = fault.getCode();
        String aNew = ErrorUtil.getProperties(fault.getMessage()).get("code");

        if (aNew != null) {
            errorCode = aNew;
        }

        InvocationException iex;

        if (isUserError(errorCode)) {
            log.debug("throws userDefined Exception : " + fault);
            iex = new UserDefineException(fault);
        } else {
            log.debug("throws Invocation Exception : " + fault);
            iex = new InvocationException(fault);
        }

        Object stacktrace = iex.get("stacktrace");
        String stackMessage = "";

        if (stacktrace != null) {
            stackMessage = stacktrace.toString();
        }

        Object message = iex.get("message");
        log.error(message == null ? "" : message.toString() + "\nPrint StackTrace :\n" + stackMessage);
        throw iex;
    }
}
